<?php
namespace Face\Controller;
class DingController extends CommonController {
    /*收货地址为空*/
    public function er()
    {
        $this->display();
    }
    /*确认收货*/
    public function queren()
    {
        $id = i('get.id');
        $data = [
            'where'=>3,
        ];
        M('ding')->where(['id'=>$id])->save($data);
        $this->display();
    }
    /*购买失败*/
    public function shibai()
    {
        $this->display();
    }
    /*提交订单*/
    public function index()
    {
        $id = i('get.id');
        $post = i('post.');
        $dizhi  = M('add')->where(['openid'=>$_SESSION['wechatopenid'],'add_moren'=>1])->find();
        $good = M('goods')->where(['id'=>$id])->find();



        /*库存*/
        $kucun = $good['goods_kucun']-1;

        /*成交量*/
        $chengjiao = $good['goods_chengjiao']+1;

        $data1 = [
            'goods_kucun'=>$kucun,
            'goods_chengjiao'=>$chengjiao,
        ];

        $this->assign('voi',$dizhi);
        $this->assign('vo',$good);
        if(IS_POST){
            /*如果购买数量等于0*/
            if($post['dizhi']==NULL){
                $this->redirect('Face/Ding/er');
            }
            if($post['number1']==0){
                $zong = $good['goods_xiaoshou'];
                $data = [
                    'goodid'=>$id,
                    'openid'=>$_SESSION['wechatopenid'],
                    'dizhi'=>$post['dizhi'],
                    'num'=>1,
                    'goodname'=>$good['goods_name'],
                    'money'=>$zong,
                    'time'=>time(),
                    'dingnum'=>'D'.time().rand(0,9).rand(0,9),rand(0,9),
                    'youfei'=>$good['goods_youfei'],
                ];
                if(M('ding')->add($data)){
                    M('goods')->where(['id'=>$id])->save($data1);

                    $idd = M('ding')->getLastInsID();
                    $this->redirect('Face/Ding/wechatpay', array('id' => $idd), 0, NULL);
                }else{
                    $this->redirect('Face/Ding/shibai');
                }
                /*如果购买数量不等于0*/
            }else{
                $zong = $good['goods_xiaoshou']*$post['number1'];
                $data = [
                    'goodid'=>$id,
                    'openid'=>$_SESSION['wechatopenid'],
                    'dizhi'=>$post['dizhi'],
                    'num'=>$post['number1'],
                    'goodname'=>$good['goods_name'],
                    'money'=>$zong,
                    'time'=>time(),
                    'dingnum'=>'D'.time().rand(0,9).rand(0,9),rand(0,9),
                    'youfei'=>$good['goods_youfei'],
                ];
                if(M('ding')->add($data)){
                    M('goods')->where(['id'=>$id])->save($data1);

                    $idd = M('ding')->getLastInsID();
                    $this->redirect('Face/Ding/wechatpay', array('id' => $idd), 0, NULL);
                }else{
                    $this->redirect('Face/Ding/shibai');
                }
            }
        }else {
            $this->display();
        }
    }

    //在类初始化方法中，引入相关类库
    public function _initialize() {
        vendor('Alipay.Corefunction');
        vendor('Alipay.Md5function');
        vendor('Alipay.Notify');
        vendor('Alipay.Submit');

        vendor('lib.JsApiPay');
        Vendor('lib.log');
    }
    /*微信pay*/
    public function wechatpay()
    {

        $id = i('get.id');
        $data = M('ding')->where(['id'=>$id])->find();

        $money = $data['money'];
        $youfei = $data['youfei'];
        $zong = $money+$youfei;
        //①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();

        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("test");
        $input->SetAttach("test");
        $out_trade_no = \WxPayConfig::MCHID.date("YmdHis");
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($zong*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 3600));

        $input->SetGoods_tag("test");
        /*成功回调页面*/
        $input->SetNotify_url('http://www.amijie.top/index.php?g=Face&m=Ding&a=wxpayed&id='.$id);

        //$input->SetProduct_id($order_sn);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $appid = \WxPayConfig::APPID;
        $input->SetAppid($appid);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        //获取共享收货地址js函数参数
        $editAddress = $tools->GetEditAddressParameters();
        $this->assign('openId',$openId);
        $this->assign('editAddress',$editAddress);
        $this->assign('jsApiParameters',$jsApiParameters);

        $this->assign('id',$id);
        $this->display();

    }
    /*微信成功的回调页面*/
    public function wxpayed()
    {
        $id = i('get.id');
        $data = [
            'where'=>1,
        ];
        /*给用户加积分*/
        $good = M('goods')->where(['id'=>$id])->find();
        $my = M('wechatuser')->where(['openid'=>$_SESSION['wechatopenid']])->find();
        $jifen = $my['jifen']+$good['goods_jifen'];

        $data3  = [
            'jifen'=>$jifen,
        ];
        $data4 = [
            'openid'=>$_SESSION['wechatopenid'],
            'text'=>'购买商品获得积分 + '.$jifen,
            'time'=>time(),
        ];
        if(M('ding')->where(['id'=>$id])->save($data)){
            M('wechatuser')->where(['openid'=>$_SESSION['wechatopenid']])->save($data3);
            M('fankuijilu')->add($data4);
            $this->redirect('Face/Ding/buy');
        }else{
            $this->error('购买失败');
        }
    }
    /*购买成功页面*/
    public function buy()
    {
        $this->display();
    }
    /*支付宝pay*/
    public function pay()
    {
        $alipay_config=C('alipay_config');

        $payment_type = "1"; //支付类型 //必填，不能修改
        $notify_url = C('alipay.notify_url'); //服务器异步通知页面路径
        $return_url = C('alipay.return_url'); //页面跳转同步通知页面路径
        $seller_email = C('alipay.seller_email');//卖家支付宝帐户必填

        $id = i('get.id');
        $data = M('ding')->where(['id'=>$id])->find();

        $out_trade_no = $data['dingnum'];//商户订单号 通过支付页面的表单进行传递，注意要唯一！
        $subject = $data['goodname'];  //订单名称 //必填 通过支付页面的表单进行传递
        $total_fee = $data['money'];   //付款金额  //必填 通过支付页面的表单进行传递
        $body = '';  //订单描述 通过支付页面的表单进行传递
        $show_url = '';  //商品展示地址 通过支付页面的表单进行传递
        $anti_phishing_key = "";//防钓鱼时间戳 //若要使用请调用类文件submit中的query_timestamp函数
        $exter_invoke_ip = get_client_ip(); //客户端的IP地址

        $parameter = array(
            "service" => "create_direct_pay_by_user",
            "partner" => trim($alipay_config['partner']),
            "payment_type"    => $payment_type,
            "notify_url"    => $notify_url,
            "return_url"    => $return_url,
            "seller_email"    => $seller_email,
            "out_trade_no"    => $out_trade_no,
            "subject"    => $subject,
            "total_fee"    => $total_fee,
            "body"            => $body,
            "show_url"    => $show_url,
            "anti_phishing_key"    => $anti_phishing_key,
            "exter_invoke_ip"    => $exter_invoke_ip,
            "_input_charset"    => trim(strtolower($alipay_config['input_charset']))
        );

        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"post", "确认");
        echo $html_text;
    }

    public function notifyurl(){

        $alipay_config=C('alipay_config');
        $alipayNotify = new \AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();

        if($verify_result) {
            //验证成功
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            $out_trade_no   = $_POST['out_trade_no'];      //商户订单号
            $trade_no       = $_POST['trade_no'];          //支付宝交易号
            $trade_status   = $_POST['trade_status'];      //交易状态
            $total_fee      = $_POST['total_fee'];         //交易金额
            $notify_id      = $_POST['notify_id'];         //通知校验ID。
            $notify_time    = $_POST['notify_time'];       //通知的发送时间。格式为yyyy-MM-dd HH:mm:ss。
            $buyer_email    = $_POST['buyer_email'];       //买家支付宝帐号；
            $parameter = array(
                "out_trade_no"     => $out_trade_no, //商户订单编号；
                "trade_no"     => $trade_no,     //支付宝交易号；
                "total_fee"     => $total_fee,    //交易金额；
                "trade_status"     => $trade_status, //交易状态
                "notify_id"     => $notify_id,    //通知校验ID。
                "notify_time"   => $notify_time,  //通知的发送时间。
                "buyer_email"   => $buyer_email,  //买家支付宝帐号；
            );
            if($_POST['trade_status'] == 'TRADE_FINISHED') {
                //
            }else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {                           if(!checkorderstatus($out_trade_no)){
                orderhandle($parameter);
                //进行订单处理，并传送从支付宝返回的参数；
            }
            }
            echo "success";        //请不要修改或删除
        }else {
            //验证失败
            echo "fail";
        }
    }

    public function returnurl()
    {
        $alipay_config=C('alipay_config');
        $alipayNotify = new \AlipayNotify($alipay_config);//计算得出通知验证结果
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result) {
            //验证成功
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
            $out_trade_no   = $_GET['out_trade_no'];      //商户订单号
            $trade_no       = $_GET['trade_no'];          //支付宝交易号
            $trade_status   = $_GET['trade_status'];      //交易状态
            $total_fee      = $_GET['total_fee'];         //交易金额
            $notify_id      = $_GET['notify_id'];         //通知校验ID。
            $notify_time    = $_GET['notify_time'];       //通知的发送时间。
            $buyer_email    = $_GET['buyer_email'];       //买家支付宝帐号；

            $parameter = array(
                "out_trade_no"     => $out_trade_no,      //商户订单编号；
                "trade_no"     => $trade_no,          //支付宝交易号；
                "total_fee"      => $total_fee,         //交易金额；
                "trade_status"     => $trade_status,      //交易状态
                "notify_id"      => $notify_id,         //通知校验ID。
                "notify_time"    => $notify_time,       //通知的发送时间。
                "buyer_email"    => $buyer_email,       //买家支付宝帐号
            );

            if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                if(!checkorderstatus($out_trade_no)){
                    orderhandle($parameter);  //进行订单处理，并传送从支付宝返回的参数；
                }
                $this->redirect(C('alipay.successpage'));//跳转到配置项中配置的支付成功页面；
            }else {
                echo "trade_status=".$_GET['trade_status'];
                $this->redirect(C('alipay.errorpage'));//跳转到配置项中配置的支付失败页面；
            }
        }else {
            //验证失败
            //如要调试，请看alipay_notify.php页面的verifyReturn函数
            echo "支付失败！";
        }
    }


    /*未付款订单详情  待发货订单*/
    public function content()
    {
        $id = i('get.id');
        $count      = M('ding')->where(['openid'=>$_SESSION['wechatopenid'],'id'=>$id])->count();// 查询满足要求的总记录数
        if($count==0){
            $this->redirect('Face/Ding/kong');
        }
        $Page       = new \Think\Page($count,30);// 实例化分页类 传入总记录数和每页显示的记录数(10)
        $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show       = $Page->show();// 分页显示输出

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = M('ding')->where(['openid'=>$_SESSION['wechatopenid'],'id'=>$id])->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        /*0为未付款 1为已付款代发货 2为已发货 3为交易成功*/
        foreach ($list as $k => $v){
            $list[$k]['goodid'] = M('goods')->where(['id' => $v['goodid']])->find();
            $list[$k]['dizhi'] = M('add')->where(['id' => $v['dizhi']])->find();
        }

        /*
        echo '<pre/>';
        var_dump($list);
        die();
        */

        $data = M('kuaidi')->where(['did'=>$id])->find();

        $this->assign(['page'=>$show,'data'=>$list,'voi'=>$data]);

        $this->display();
    }
    /*删除订单成功*/
    public function delok()
    {
        $this->display();
    }
    /*删除订单*/
    public function delding()
    {
        $id = i('get.id');
        if(M('ding')->where(['openid'=>$_SESSION['wechatopenid'],'id'=>$id])->delete()){
            $this->redirect('Face/Ding/delok');
        }else{
            $this->error('未知错误~');
        }
    }

    /*待收货*/
    public function daishouhuo()
    {
        $where  = i('get.where');
        $count      = M('ding')->where(['openid'=>$_SESSION['wechatopenid'],'where'=>$where])->count();// 查询满足要求的总记录数
        if($count==0){
            $this->redirect('Face/Ding/kong');
        }
        $Page       = new \Think\Page($count,30);// 实例化分页类 传入总记录数和每页显示的记录数(10)
        $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show       = $Page->show();// 分页显示输出

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = M('ding')->where(['openid'=>$_SESSION['wechatopenid'],'where'=>$where])->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        /*0为未付款 1为已付款代发货 2为已发货 3为交易成功*/
        foreach ($list as $k => $v){
            $list[$k]['goodid'] = M('goods')->where(['id' => $v['goodid']])->find();
            $list[$k]['dizhi'] = M('add')->where(['id' => $v['dizhi']])->find();
        }
        /*
        echo '<pre/>';
        var_dump($list);
        die();
        */
        $this->assign(['page'=>$show,'data'=>$list]);

        $this->display();
    }
    /*待发货*/
    public function daifahuo()
    {
        $where  = i('get.where');

        $count      = M('ding')->where(['openid'=>$_SESSION['wechatopenid'],'where'=>$where])->count();// 查询满足要求的总记录数
        if($count==0){
            $this->redirect('Face/Ding/kong');
        }
        $Page       = new \Think\Page($count,30);// 实例化分页类 传入总记录数和每页显示的记录数(10)
        $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show       = $Page->show();// 分页显示输出

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = M('ding')->where(['openid'=>$_SESSION['wechatopenid'],'where'=>$where])->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        /*0为未付款 1为已付款代发货 2为已发货 3为交易成功*/
        foreach ($list as $k => $v){
            $list[$k]['goodid'] = M('goods')->where(['id' => $v['goodid']])->find();
            $list[$k]['dizhi'] = M('add')->where(['id' => $v['dizhi']])->find();
        }
        /*
        echo '<pre/>';
        var_dump($list);
        die();
        */
        $this->assign(['page'=>$show,'data'=>$list]);

        $this->display();
    }
    /*待付款订单*/
    public function other()
    {
        $where  = i('get.where');

        $count      = M('ding')->where(['openid'=>$_SESSION['wechatopenid'],'where'=>$where])->count();// 查询满足要求的总记录数
        if($count==0){
            $this->redirect('Face/Ding/kong');
        }
        $Page       = new \Think\Page($count,30);// 实例化分页类 传入总记录数和每页显示的记录数(10)
        $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show       = $Page->show();// 分页显示输出

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = M('ding')->where(['openid'=>$_SESSION['wechatopenid'],'where'=>$where])->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        /*0为未付款 1为已付款代发货 2为已发货 3为交易成功*/
        foreach ($list as $k => $v){
            $list[$k]['goodid'] = M('goods')->where(['id' => $v['goodid']])->find();
            $list[$k]['dizhi'] = M('add')->where(['id' => $v['dizhi']])->find();
        }
        /*
        echo '<pre/>';
        var_dump($list);
        die();
        */
        $this->assign(['page'=>$show,'data'=>$list]);

        $this->display();

    }
    /*所有订单*/
    public function all()
    {
        $data = M('ding')->where(['openid'=>$_SESSION['wechatopenid']])->select();

        $count      = M('ding')->where(['openid'=>$_SESSION['wechatopenid']])->count();// 查询满足要求的总记录数
        if($count==0){
            $this->redirect('Face/Ding/kong');
        }
        $Page       = new \Think\Page($count,30);// 实例化分页类 传入总记录数和每页显示的记录数(10)
        $Page->setConfig('theme',"%HEADER% %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");
        $show       = $Page->show();// 分页显示输出

        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = M('ding')->where(['openid'=>$_SESSION['wechatopenid']])->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        /*0为未付款 1为已付款代发货 2为已发货 3为交易成功*/
        foreach ($list as $k => $v){
            $list[$k]['goodid'] = M('goods')->where(['id' => $v['goodid']])->find();
            $list[$k]['dizhi'] = M('add')->where(['id' => $v['dizhi']])->find();
        }

        $this->assign(['page'=>$show,'data'=>$list]);

        $this->display();
    }
    /*确认收货*/
    public function okok()
    {
        $id = i('get.id');
        $data = [
            'where'=>3,
        ];
        if(M('ding')->where(['id'=>$id])->save($data)){
            $this->redirect('Face/Ding/all');
        }else{
            $this->error('失败，未知错误');
        }
    }
    /*空订单*/
    public function kong()
    {
        $this->display();
    }
}